
<template>
  <div class="app-container">
    <div class="body-container mt0">
      <el-row :gutter="20">
        <!--单位数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入单位名称" clearable size="small" prefix-icon="el-icon-search"
              style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
              @node-click="handleNodeClick" />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <div class="search-container">
            <div class="search-title">
              查询条件
            </div>
            <div class="search-form">
              <div class="form-row">
                <div class="form-column">
                  <span class="column-title">姓名</span>
                  <el-input v-model="queryParams.personnelName" placeholder="请输入" class="input-w150" clearable
                    @keyup.enter.native="handleQuery" />
                </div>
                <div class="form-column">
                  <span class="column-title">单位</span>
                  <treeselect class="input-w150" v-model="queryParams.unitCode" :options="deptTreeList"
                    :show-count="true" placeholder="请选择" />
                </div>
                <div class="form-column">
                  <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                  <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </div>
              </div>
            </div>
          </div>


          <div class="body-container">
            <div class="operation-bar">
              <div class="bar-title">
                用户列表
              </div>
              <div class="bar-btn__wrapper">
                <div class="bar-btn" @click="handleAdd"><i class="el-icon-plus"></i>新增</div>
              </div>
            </div>


            <el-table v-loading="loading" :data="userList" stipe>
              <el-table-column type="index" label="#" align="center" min-width="100"></el-table-column>
              <el-table-column label="用户名" align="center" key="personnelName" prop="personnelName" />
              <el-table-column label="负责人" align="center" key="commander" prop="commander" />
              <el-table-column label="手机号码" align="center" key="mobilePhone" prop="mobilePhone" />
              <el-table-column label="座机" align="center" key="landlinePhone" prop="landlinePhone" />
              <el-table-column label="归属单位" align="center" key="unitCode" prop="" >
                <template slot-scope="scope">
                  {{ scope.row.unitCode ?  findLabelById(deptOptions, scope.row.unitCode) : '' }}
                </template>
                </el-table-column>
              <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
                <div class="table-option" slot-scope="scope">
                  <!-- <span @click="handleToDetail(scope.row)">详情</span> -->
                  <span @click="handleEdit(scope.row)">编辑</span>
                  <!-- <span @click="handleAddData(scope.row)"
                    v-if="scope.row.personnelName != 'admin' && scope.row.talentStatus == false">添加到人才库</span> -->
                  <span class="danger" v-if="scope.row.personnelName != 'admin'"
                    @click="handleDelete(scope.row)">删除</span>
                  <!-- <span class="danger" v-if="scope.row.personnelName != 'admin'"
                    @click="handleRestPwd(scope.row)">重置密码</span> -->
                </div>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 新增或编辑用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-row>
              <el-col :span="8">
                <el-form-item label="用户名" prop="personnelName">
                  <el-input v-model="form.personnelName" class="input180" placeholder="请输入" maxlength="20" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="登陆名" prop="loginName" v-if="actionType == 'add'">
                  <el-input v-model="form.loginName" class="input180" placeholder="请输入" maxlength="20" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="密码" prop="password" v-if="actionType == 'add'">
                  <el-input v-model="form.password" type="password" class="input180" placeholder="请输入" maxlength="16"
                    clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="负责人" prop="commander">
                  <el-input v-model="form.commander" class="input180" placeholder="请输入" maxlength="16" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="手机号" prop="mobilePhone">
                  <el-input v-model="form.mobilePhone" class="input180" placeholder="请输入" maxlength="16" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="座机" prop="landlinePhone">
                  <el-input v-model="form.landlinePhone" class="input180" placeholder="请输入" maxlength="16" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="归属单位" prop="unitCode">
                  <treeselect class="input180" style="margin-bottom: 0px;" v-model="form.unitCode"
                    :options="deptOptions" :show-count="true" placeholder="请选择" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
              <el-form-item label="角色"  prop="roleIdList">
                <el-select v-model="form.roleIdList" class="input180" placeholder="请选择" clearable filterable>
                  <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                    :value="item.roleId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            </el-row>
            <el-row>
       
            </el-row>

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="用户导入" :visible.sync="uploadialog" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="fileHeaders" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>

          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="downloadExcel">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="uploadDisable" :loading="uploadDisable" @click="submitFileForm">确
          定</el-button>
        <el-button @click="uploadialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码按钮操作 -->
    <el-dialog title="重置密码" :visible.sync="restPwdDialog" width="30%">
      <el-form ref="resPwdFrom" :model="resPwdFrom" :rules="resPwdRules" label-width="80px">
        <el-form-item label="密码配置" prop="configId">
          <el-select v-model="resPwdFrom.configId" placeholder="请选择" clearable filterable class="input180">
            <el-option v-for="dict in dict.type.sys_normal_pwd" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="restPwdDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitResetPwd('resPwdFrom')">确 定</el-button>
      </span>
    </el-dialog>


    <UserDetail :id="personnelId" :visible.sync="userDialog"></UserDetail>
  </div>
</template>

<script>
import UserDetail from '@/components/userDetail.vue'
import { roleOptionSelect } from "@/api/role";
import { addUser, delUser, updateUser, getUserProfile, resetUserPwd, exportPersonnelList } from '@/api/system/user'
import { deptTree, deptList, excludeDeptList, personnelList, deptAdd, deptUpdate, deptDel } from "@/api/org";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import provinceJson from "../system/user/province.json";
import { addPersonalTalent } from "@/api/talent";
import { getDeptName } from "@/utils/ruoyi";

export default {
  name: "User",
  dicts: ['sys_police_rank_code', 'sys_exit_year', 'sys_military_status', 'sys_political_status', 'sys_normal_pwd', 'sys_user_staff_status', 'sys_position_code', 'sys_user_blood_type', 'sys_user_major_code'],
  components: { Treeselect, UserDetail },
  data() {
    return {
      uploadDisable: false,
      upload: {
        isUploading: false,
        updateSupport: 0,
        url: process.env.VUE_APP_BASE_API + '/personnel/importPersonnel',
      },
      uploadialog: false,
      resPwdFrom: {},
      restPwdDialog: false,
      actionType: 'add',
      roleList: [],
      userList: [],
      deptName: '',
      fileAction: process.env.VUE_APP_BASE_API + '/common/upload',
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],  //图片
      chinaLocations: provinceJson, //省市区json
      resPwdRules: {
        configId: [
          { required: true, message: "配置不能为空", trigger: "blur" }
        ]
      },
      rules: {
        // personnelName: [
        //   { required: true, message: "用户名称不能为空", trigger: "blur" },
        //   { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        // ],

        // workingStatus: [
        //   { required: true, message: "在位状态不能为空", trigger: "blur" }
        // ],
        // enlistmentTime: [
        //   { required: true, message: "入伍时间不能为空", trigger: "blur" }
        // ],
        // gender: [
        //   { required: true, message: "用户性别不能为空", trigger: "blur" }
        // ],
        // militaryStatus: [
        //   { required: true, message: "军籍状态不能为空", trigger: "blur" }
        // ],
        // politicalStatus: [
        //   { required: true, message: "政治面貌不能为空", trigger: "blur" }
        // ],

        // dateOfBirth: [
        //   { required: true, message: "用户出生日期不能为空", trigger: "blur" }
        // ],
        // unitCode: [
        //   { required: true, message: "用户归属单位不能为空", trigger: "blur" }
        // ],
       loginName: [
         { required: true, message: "登录不能为空", trigger: "blur" }
       ],
        password: [
        { required: true, message: "登录密码不能为空", trigger: "blur" },
         { min: 5, max: 20, message: '登录密码长度必须介于 5 和 20 之间', trigger: 'blur' }
       ],
      },
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      title: "",
      deptOptions: undefined,
      open: false,
      dateRange: [],
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      userDialog: false,
      personnelId: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  computed: {
    downloadUrl() {
      return process.env.VUE_APP_DOWNLOAD_URL
    },
    deptTreeList() {
      return this.$store.state.user.deptTreeList
    },
    deptList() {
      return this.$store.state.user.deptList
    },
  },
  watch: {
    // 根据名称筛选单位树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getRoleList();
  },
  methods: {
    findLabelById(data, targetId, path = []) {
      for (const item of data) {
        const currentPath = [...path, item.label];
        if (item.id == targetId) {
          return currentPath.join('/');
        }
        if (item.children) {
          const found = this.findLabelById(item.children, targetId, currentPath);
          if (found) {
            return found;
          }
        }
      }
      return '';
    },
    async handleDownLoad() {
      let params = {
        userType: 1,
        ...this.queryParams
      }
      let res = await exportPersonnelList(params);
      let blob = new Blob([res], {
        type: "application/octet-stream"
      });
      let objectUrl = URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.href = objectUrl;
      a.setAttribute("download", "用户信息.xlsx");
      a.click();
      window.URL.revokeObjectURL(blob);
    },
    // 新增到人才库
    async handleAddData(row) {
      let sourceObj = {
        "personnelId": row.id,
      }
      let res = await addPersonalTalent(sourceObj)
      if (res.code === 200) {
        this.$modal.msgSuccess("添加成功");
      } else {
        this.$modal.msgWarning(res.msg);
      }
    },
    // 计算时间差
    countYearFun(val) {
      if (val == '') {
        return ''
      }
      let year = 0;
      var today = new Date();
      var birthDate = new Date(val);
      year = today.getFullYear() - birthDate.getFullYear();
      var monthDiff = today.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        year--;
      }
      return year
    },

    handleToDetail(row) {
      this.userDialog = true;
      this.personnelId = String(row.id)
    },
    // 获取权限列表
    async getRoleList() {
      const res = await roleOptionSelect()
      // console.log(res)
      if (res.code === 200) {
        let tmpList = res.data
        this.roleList = tmpList.filter(item => {
          // return item.roleKey !== 'common'
          return item
        })
        // this.roleIdList = res.data
      }
    },
    getDeptName(id) {
      return getDeptName(this.deptList, id)
    },
    // 文件上传前检查
    beforeFileUpload(file) {
      var FileExt = file.name.replace(/.+\./, "");
      const isLtM = file.size / 1024 / 1024 < 150;
      const fileTypeList = ['jpg', 'jpeg', 'png']
      let isFileType = fileTypeList.indexOf(FileExt.toLowerCase()) > -1
      if (!isFileType || !isLtM) {
        this.$message.error('请检查文件格式以及大小');
      }
      return isFileType && isLtM;
    },
    // 文件上传成功
    handleImageSuccess(res, file) {
      if (res.code === 200) {
        this.fileList.push({
          name: file.originalFilename,
          fileName: res.fileName,
          url: this.downloadUrl + res.fileName
        })
      }
    },
    // 文件删除
    handleRemove(file, fileList) {
      this.fileList = [];
      console.log(this.fileList)
      // let index = fileList.indexOf(file);
      // this.fileList.splice(index, 1)
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      let params = {
        userType: 1,
        ...this.queryParams
      }
      personnelList(params).then(response => {
        if (response.code == 200) {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        } else {
          this.loading = false;
          this.$message.error(response.msg)
        }
      });
    },
    /** 查询单位下拉树结构 */
    getDeptTree() {
      deptTree().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.unitCode = data.id;
      this.handleQuery();
    },
    // 用户状态编辑
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }
      this.dateRange = [];
      this.queryParams.unitCode = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.fileList = [];
      this.actionType = 'add',
        this.title = "新增用户";
    },
    /** 编辑按钮操作 */
    handleEdit(row) {
      this.reset();
      const userId = row.id;
      getUserProfile(userId).then(response => {
        response.data.bloodType = String(response.data.bloodType)
        response.data.workingStatus = String(response.data.workingStatus)
        response.data.politicalStatus = String(response.data.politicalStatus)
        response.data.militaryStatus = String(response.data.militaryStatus)
        this.form = response.data;
        if (response.data.roleIdList) {
          this.form.roleIdList = response.data.roleIdList[0];
        }

        if (response.data.personnelPic) {
          this.fileList = [{
            name: response.data.personnelPic,
            url: this.downloadUrl + response.data.personnelPic
          }]
        }
        if (response.data.provinceCode) {
          this.form.jiguan = [response.data.provinceCode, response.data.cityCode, response.data.areaCode]
        } else {
          this.form.jiguan = []
        }
        this.open = true;
        this.title = "编辑用户";
        this.actionType = 'edit'
      });
    },
    /** 重置密码按钮操作 */
    handleRestPwd(row) {
      let that = this;
      this.$modal.confirm('是否确认重置密码?').then(async function (res) {
        if (res == 'confirm') {
          let pwd = that.dict.type.sys_normal_pwd[0].value
          let params = {
            personnelId: row.id,
            password: pwd,
          }
          resetUserPwd(params).then(response => {
            that.$modal.msgSuccess("重置成功");
          });
        }
      }).then(() => {
        that.getList();
      }).catch(() => { });
    },

    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = {
            userType: 1,
            ...this.form
          }
          if (this.form.roleIdList) {
              params.roleId = this.form.roleIdList;
              delete params.roleIdList;
            }
          if (params.id != undefined) {
            delete params.password;
            delete params.loginName;
            delete params.talentStatus;
            updateUser(params).then(response => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
              this.$store.dispatch('GetUserList')
            });
          } else {
            addUser(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$store.dispatch('GetUserList')
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let that = this;
      this.$modal.confirm('是否确认删除?').then(async function (res) {
        if (res == 'confirm') {
          let response = await delUser(row.id)
          if (response.code == 200) {
            that.$message.success('删除成功')
          } else {
            that.$message.error(response.msg)
          }
        }
      }).then(() => {
        this.getList();
      }).catch(() => { });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.uploadialog = true
    },
    /** 下载模板操作 */
    downloadExcel() {
      let a = document.createElement('a')
      a.href = '/static/user_template.xlsx'
      a.download = '导入用户模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    // // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadialog = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.uploadDisable = false;
      if (response.code == 200) {
        this.$message.success('导入成功！')
      } else {
        this.$message.error(response.msg)
      }
      this.getList();
    },
    // // 提交上传文件
    submitFileForm() {
      this.uploadDisable = true;
      this.$refs.upload.submit()
    }
  }
};
</script>
<style>
.input180 {
  display: block;
  width: 170px !important;
}

.disabled .el-upload.el-upload--picture-card {
  display: none !important;
}

.disabled .el-button--success.is-plain {
  display: none !important;
}

.hide .el-upload--picture-card {
  display: none;
}

.manColor {
  color: red;
}
</style>
